package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.UserLike;
import com.itheima.service.mongo.DataTotalService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class DataTotalServiceImpl implements DataTotalService {

    @Autowired
    MongoTemplate mongoTemplate;

    //喜欢 粉丝 互相喜欢 数据查询
    @Override
    public Map<String, Integer> DataTotal(Long userId) {
        //根据用户id查询 如果该用户被对方喜欢 则为粉丝 如也喜欢对方则为互相喜欢 如果该用户喜欢对方 对方未喜欢该用户则为喜欢

        Integer eachLoveCount = 0; //互相喜欢
        Integer loveCount = 0; //喜欢
        Integer fanCount = 0; //粉丝

        //查询该用户被喜欢的数据
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        //遍历所有被喜欢的数据
        if (CollUtil.isNotEmpty(userLikes)) {
            for (UserLike userLike : userLikes) {
                Long id = userLike.getUserId();
                //互相喜欢
                Query query1 = new Query(Criteria.where("likeUserId").is(id).and("userId").is(userId));
                boolean eCount = mongoTemplate.exists(query1, UserLike.class);
                if (eCount){
                    eachLoveCount++;
                }

                //粉丝
                Query query2 = new Query(Criteria.where("likeUserId").is(id).and("userId").is(userId));
                boolean fCount = mongoTemplate.exists(query2, UserLike.class);
                if (!fCount){
                    fanCount++;
                }
            }
        }
        //喜欢
        Query query3 = new Query(Criteria.where("userId").is(userId));
        //查询当前用户喜欢别人数据 我喜欢别人 但是别人没喜欢我
        List<UserLike> likeList = mongoTemplate.find(query3, UserLike.class);
        if (CollUtil.isNotEmpty(likeList)){
            for (UserLike userLike : likeList) {
                Long id = userLike.getLikeUserId();

                Query query4 = new Query(Criteria.where("userId").is(id).and("likeUserId").is(userId));

                boolean exists = mongoTemplate.exists(query4, UserLike.class);
                if (!exists){
                    loveCount++;
                }

            }

        }
        Map<String,Integer> map = new HashMap<>();
        map.put("eachLoveCount",eachLoveCount);
        map.put("loveCount",loveCount);
        map.put("fanCount",fanCount);

        return map;
    }
}
